package com.chuanjiabao.wisdom.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.model.GeneratePresignedUrlRequest;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.adapter.MonthAdapter;
import com.chuanjiabao.wisdom.bean.FamilyResCallbackBean;
import com.chuanjiabao.wisdom.bean.ImageBean;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.databinding.FragmentFamilyTextBinding;
import com.chuanjiabao.wisdom.ui.activity.FamilyPeopleFilesActivity;
import com.chuanjiabao.wisdom.ui.activity.UpdateTextActivity;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeHelper;
import com.chuanjiabao.wisdom.util.dialog.PermissionDialog;
import com.lzy.okgo.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.alibaba.sdk.android.oss.common.HttpMethod.GET;

@SuppressLint("ValidFragment")
public class FamilyTextFragment extends BaseLazyFragment {

    FragmentFamilyTextBinding binding;

    String homeId, peopleId;
    OSSClient oss;

    String bucketName = "";
    //图片/视频
    List<String> fileIds = new ArrayList<>();
    List<String> fileIdsSecond = new ArrayList<>();
    List<ImageBean> listItemLocations = new ArrayList<>();
    List<ImageBean> listItemLocationsSecond = new ArrayList<>();
    //文本
    List<String> fileIdsText = new ArrayList<>();
    List<String> fileIdsSecondText = new ArrayList<>();
    List<ImageBean> listItemLocationsText = new ArrayList<>();
    List<ImageBean> listItemLocationsSecondText = new ArrayList<>();
    Map<String, List<FamilyResCallbackBean.DataBeanX.DataBean>> maps = new HashMap<>();
    List<FamilyResCallbackBean.DataBeanX.DataBean> listDataSecond = new ArrayList<>();
    List<String> months = new ArrayList<>();
    MonthAdapter monthAdapter;

    public FamilyTextFragment(OSSClient oss, String homeId, String peopleId) {
        this.oss = oss;
        this.homeId = homeId;
        this.peopleId = peopleId;
    }

    @Override
    public int setLayoutId() {
        return R.layout.fragment_family_text;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(
                LayoutInflater.from(getActivity()),
                R.layout.fragment_family_text,
                container,
                false
        );
        binding.setFragment(this);
        initView();
        EventBus.getDefault().register(this);
        return binding.getRoot();
    }

    private void initView() {
        monthAdapter = new MonthAdapter(getActivity(), months, maps, false, false);
        binding.recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recycler.setItemAnimator(new DefaultItemAnimator());
        ((SimpleItemAnimator) binding.recycler.getItemAnimator()).setSupportsChangeAnimations(false);
        binding.recycler.setAdapter(monthAdapter);
        monthAdapter.setOnThirdClickListener((first, second, third, url) -> {
            if (4 == third) {
                //文本
                if (!fileIdsText.contains(second + "")) {
                    fileIdsText.add(second + "");
                    listItemLocationsText.add(new ImageBean(first, second, third));
                } else {
                    fileIdsSecondText = fileIdsText;
                    fileIdsSecondText.remove(second + "");
                    fileIdsText = fileIdsSecondText;

                    listItemLocationsSecondText = listItemLocationsText;
                    for (ImageBean iv : listItemLocationsText) {
                        if (iv.getFirst() == first && iv.getSecond() == second) {
                            listItemLocationsSecondText.remove(iv);
                        }
                    }
                    listItemLocationsText = listItemLocationsSecondText;
                }
            } else {
                //图/视频
                if (!fileIds.contains(second + "")) {
                    fileIds.add(second + "");
                    listItemLocations.add(new ImageBean(first, second, third));
                } else {
                    fileIdsSecond = fileIds;
                    fileIdsSecond.remove(second + "");
                    fileIds = fileIdsSecond;

                    listItemLocationsSecond = listItemLocations;
                    for (ImageBean iv : listItemLocations) {
                        if (iv.getFirst() == first && iv.getSecond() == second) {
                            listItemLocationsSecond.remove(iv);
                        }
                    }
                    listItemLocations = listItemLocationsSecond;
                }
            }
        });

        binding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            p = 1;
            months.clear();
            maps.clear();
            getFamilyUserInfo(homeId, peopleId, "4");
        });
        binding.refreshLayout.setOnLoadMoreListener(refreshLayout ->
                getFamilyUserInfo(homeId, peopleId, "4")
        );

        binding.llModuleAddText.setOnClickListener(this);
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void lazyLoad() {
        p = 1;
        months.clear();
        maps.clear();
        getFamilyUserInfo(homeId, peopleId, "4");
    }

    @Override
    public void onClick(View v) {
        //noinspection SwitchStatementWithTooFewBranches
        switch (v.getId()) {
            case R.id.llModuleAddText:
                if (TextUtils.equals("3", IndexFragment.permissionsId)
                        && TextUtils.equals("0", IndexFragment.uploadStatus)) {
                    new PermissionDialog(getActivity())
                            .setHint("对不起，您在该家没有上传权限")
                            .show();
                    return;
                }

                Intent intent = new Intent(getActivity(), UpdateTextActivity.class);
                intent.putExtra("module_homeId", homeId);
                intent.putExtra("module_peopleId", peopleId);
                intent.putExtra("module_from", "detail");
                startActivity(intent);
                break;
            default:
        }
    }

    int p = 1;

    public void getFamilyUserInfo(final String id, String uId, String type) {
        binding.recycler.setFocusable(false);
        HTTPAPI.getInstance().getFamilyUserInfo(p++ + "", id, uId, type, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("个人文本-->" + s);
                binding.refreshLayout.finishLoadMore();
                binding.refreshLayout.finishRefresh();
                if (!StringUtil.isFail(s)) {
                    p--;
                    StringUtil.showFail(getActivity(), s);
                } else {
                    FamilyResCallbackBean listB = GsonUtil.GsonToBean(s, FamilyResCallbackBean.class);
                    listDataSecond = listB.getData().getData();
                    if (listDataSecond.size() > 0) {
                        for (FamilyResCallbackBean.DataBeanX.DataBean dataBean : listDataSecond) {
                            String createTime = dataBean.getCreate_time();
                            String dateNow = TimeHelper.getInstance().getNowTime("yyyy年MM月dd日");
                            String m = TimeHelper.getInstance()
                                    .stringToString(
                                            "yyyy-MM-dd HH:mm:ss",
                                            "yyyy年MM月dd日",
                                            createTime
                                    );

                            if (TextUtils.equals(dateNow, m)) {
                                m = "今天";
                            } else if (TextUtils.equals(
                                    dateNow.substring(0, 4),
                                    m.substring(0, 4)
                            )) {
                                m = TimeHelper.getInstance()
                                        .stringToString(
                                                "yyyy-MM-dd HH:mm:ss",
                                                "M月dd日",
                                                createTime
                                        );
                            }

                            bucketName = dataBean.getFile_bucket();
                            if (1 == dataBean.getFile_type()) {
                                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                                        dataBean.getFile_bucket(),
                                        dataBean.getFile(),
                                        30 * 60,
                                        GET);
                                Map<String, String> map = new HashMap<>();
                                map.put("x-oss-process", dataBean.getParams().getXossprocess());
                                map.put("test", dataBean.getParams().getTest());
                                generatePresignedUrlRequest.setQueryParameter(map);
                                try {
                                    String url = oss.presignConstrainedObjectURL(generatePresignedUrlRequest);
                                    dataBean.setThum(url);
                                } catch (ClientException e) {
                                    e.printStackTrace();
                                }
                            } else if (2 == dataBean.getFile_type()) {
                                try {
                                    String url = oss.presignConstrainedObjectURL(dataBean.getFile_bucket(),
                                            dataBean.getVideo_img(), 60 * 60);
                                    dataBean.setThum(url);
                                } catch (ClientException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (!months.contains(m)) {
                                List<FamilyResCallbackBean.DataBeanX.DataBean> dataBeansList = new ArrayList<>();
                                dataBeansList.add(dataBean);
                                months.add(m);
                                maps.put(m, dataBeansList);
                            } else {
                                if (!maps.get(m).contains(dataBean)) {
                                    maps.get(m).add(dataBean);
                                }
                            }
                        }
                    }
                    monthAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Subscribe
    public void onMessageEvent(RefreshMessageEvent event) {
        if (TextUtils.equals("detail", event.getType())
                && TextUtils.equals("4", event.getId())) {
            lazyLoad();
            ((FamilyPeopleFilesActivity)getActivity()).getHomeFileTotal();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

}
